package com.medialog.svnTest;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

public class SvnKitUtil {
	private static String url = "svn://172.26.140.27/";
	private static String name = "simkw";
	private static String password = "simkw";
	private static SVNRepository repository;

	public static void main(String[] args) {
		
		DAVRepositoryFactory.setup();		
		
		SvnKitUtil.repository = getSVNRepository(SvnKitUtil.url);
		
		List<SvnDomain> list = new ArrayList<SvnDomain>();
		SvnKitUtil.getList("/repository", list);
		
		int liSize = list.size();
		
		List<String> tmpList = new ArrayList<String>();
		for(int i = 0; i < liSize; i++){
			tmpList.add(list.get(i).getFnServletUrl());
		}
		
		int ord = 0;
		for(int i = 0; i < liSize; i++){
			SvnDomain domain = list.get(i);
			String parentPath = domain.getFnServletUrl().replace("/"+domain.getFnAlias(), "");
			
			domain.setFnId("" + i);
			domain.setFnParentId((tmpList.contains(parentPath)) ? "" + tmpList.indexOf(parentPath) : "0");
			domain.setFnOrder((i > 0 && list.get(i - 1).getFnParentId().equals(domain.getFnParentId())) ? ++ord : 0);
		}
		
		SvnKitUtil.repository.closeSession();
	}
	
	
	public static void getList(String url, List<SvnDomain> list){
		List<SVNDirEntry> ent = new ArrayList<SVNDirEntry>();
		
		try {
			SvnKitUtil.repository.getDir(url, -1, false, ent);
			Iterator<SVNDirEntry> it = ent.iterator();
						
			while(it.hasNext()){
				SVNDirEntry e = it.next();
				
				if(e.getKind() == SVNNodeKind.DIR){
					String name = e.getName();
					String path = url + "/" + name;
					/*
					domain.setFnDesc("");
					domain.setFnDesc();
					domain.setFnOwner();
					domain.setFnGroup();
					*/
					SvnDomain domain = new SvnDomain();
					domain.setFnUseYN("Y");
					domain.setFnCollapse(false);
					domain.setFnAlias(name);
					domain.setFnServletUrl(path);
					list.add(domain);
					
					SvnKitUtil.getList(path, list);
				}
			}
            
		} catch (Exception e) {
			e.getMessage();
		}
	}
	

	public static SVNRepository getSVNRepository(String url) {
		
		SVNRepository repository = null;
		
		try {
			repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
			ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
			repository.setAuthenticationManager(authManager);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return repository;
	}
}
